from flask import Blueprint,request,jsonify
from .dto import api_response as resp #本类子模块调用
from service import face_service as face_service

ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
bp = Blueprint('face', __name__, url_prefix='/api/face')

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@bp.route('/match', methods=['POST'])
def face_match():

    if 'file' not in request.files:
        return resp.Response(500, "file not found!!!", None).to_json()
    if not allowed_file(request.files['file'].filename):
        return resp.Response(500, "file not support !!!", None).to_json()
    
    file = request.files['file']
    match_reslut =  face_service.face_match(file)
    name = ""
    uuid = ""
    if match_reslut.get():
        name = match_reslut.face_data["name"]
        uuid = match_reslut.face_data["uuid"]
    result = {
        "is_match": match_reslut.get(),
        "name": name,
        "uuid": uuid      
    }
    return resp.Response(0, "", result).to_json()
    
@bp.route('/train', methods=['POST'])
def face_train():

    if 'file' not in request.files:
        return resp.Response(500, "file not found !!!", None).to_json()
    if not allowed_file(request.files['file'].filename):
        return resp.Response(500, "file not support !!!", None).to_json()
    
    file = request.files['file']
    uuid = request.form.get('uuid')
    name = request.form.get('name')
    if uuid is None or name is None:
        return resp.Response(400, "名字 or 唯一标识 不能为空!!!", None).to_json()
    if face_service.face_train(file, uuid, name):
        return resp.Response(0, "人脸数据录入成功", None).to_json()
    return resp.Response(500, "人脸数据录入失败", None).to_json()
    

